//
//  Untitled.swift
//  Pods
//
//  Created by 100Years on 2025/5/16.
//


public class TSCollectionViewObserver {
    private weak var collectionView: UICollectionView?
    private var observers: [NSKeyValueObservation] = []
    
    public var onContentSizeChange: ((CGSize) -> Void)?
    public var onContentInsetChange: ((UIEdgeInsets) -> Void)?
    public var onContentOffsetChange: ((CGPoint) -> Void)?
    
    public init(collectionView: UICollectionView) {
        self.collectionView = collectionView
        setupObservers()
    }
    
    private func setupObservers() {
        guard let collectionView = collectionView else { return }
        
        observers.append(
            collectionView.observe(\.contentSize, options: [.new, .old]) { [weak self] (_, change) in
                guard let newSize = change.newValue, newSize != change.oldValue else { return }
                self?.onContentSizeChange?(newSize)
            }
        )
        
        observers.append(
            collectionView.observe(\.contentInset, options: [.new, .old]) { [weak self] (_, change) in
                guard let newInset = change.newValue, newInset != change.oldValue else { return }
                self?.onContentInsetChange?(newInset)
            }
        )
        
        observers.append(
            collectionView.observe(\.contentOffset, options: [.new]) { [weak self] (_, change) in
                guard let newOffset = change.newValue else { return }
                self?.onContentOffsetChange?(newOffset)
            }
        )
    }
    
    deinit {
        observers.forEach { $0.invalidate() }
    }
}



//        collectionViewObserverHandle()
//
//private var collectionViewObserver: CollectionViewObserver!
//func collectionViewObserverHandle(){
//    collectionViewObserver = TSCollectionViewObserver(collectionView: collectionComponent.collectionView)
//
//    collectionViewObserver.onContentSizeChange = { size in
//        print("collectionViewObserver 内容大小变化: \(size)")
//    }
//
//    collectionViewObserver.onContentInsetChange = { inset in
//        print("collectionViewObserver 内边距变化: \(inset)")
//    }
//
//    collectionViewObserver.onContentOffsetChange = { offset in
//        print("collectionViewObserver 偏移量变化: \(offset)")
//    }
//
//}
//
//
//func scrollViewDidScroll(_ scrollView: UIScrollView) {
//    print("contentOffset 变化: \(scrollView.contentOffset)")
//    // 实时监听偏移量变化
//}
